// pages/ranklist/ranklist.js
const app = getApp();
const util = require('../../../../utils/util.js');
const tools = require('../../../../utils/tools.js');
const api = require('../../../../utils/api.js');
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		VID: null, //练习语句id
		rankListInfo: null,//排行榜数据
		isButtonClick: false,//是否点击播放按钮
	},

	onLoad(options) {
		this.setData({
			VID: options.VID
		})
		this.rankListInfo();
	},

	onReady() {

	},
	//排行榜信息
	rankListInfo() {
		let _self = this;
		let dataDic = {
			VID: _self.data.VID,
			//VID: 35697
		};
		api.methodGetDailyVoiceRankListInfo({
			dataDic,
			success: (res) => {
				console.log('排行榜数据', res)
				if (res.data.code != 0) {
					console.log('排行榜信息加载错误');
					return
				}

				// 拼接录音url
				let length = res.data.data.RankList.length;
				for (let i = 0; i < length; i++) {
					res.data.data.RankList[i].UserVoiceFile = app.globalData.apiUrl + res.data.data.RankList[i].UserVoiceFile
				}

				_self.setData({
					rankListInfo: res.data.data.RankList
				})
			},
			fail: (res) => {
				console.log(res);
			},
			complete: (res) => {
				console.log(res.data);
			},
		})
	},
	//点击播放录音
	playRecord(e) {
		console.log("播放录音")
		console.log('先停止录音');
		innerAudioContext.stop();
		let _self = this;
		let srcStr = e.currentTarget.dataset.url;
		if (srcStr.search(/[A-z./\d]*?mp3/) == -1) {
			console.log('录音路径不正确或为空')
			return
		}
		if (_self.data.isButtonClick) {
			console.log("已经有按钮被点击，请稍后再点")
			return
		}
		_self.setData({
			isButtonClick: true
		})
		//1s后释放状态
		setTimeout(function () {
			_self.setData({
				isButtonClick: false
			})
		}, 1000);
		console.log('录音地址:', e.currentTarget.dataset.url)
		innerAudioContext.src = srcStr;
		//播放示例录音
		innerAudioContext.play();
		innerAudioContext.onEnded((res) => {
			console.log('正常停止播放', res)
			_self.setData({
				isButtonClick: false
			})
		})
		_self.addPlayNum(e.currentTarget.dataset.openid);
	},
	//增加录音播放次数
	addPlayNum(openid) {
		let _self = this;
		let dataDic = {
			VID: _self.data.VID,
			// VID: 35697,
			OpenId: openid,
			POpenId: app.globalData.openId
		};
		api.methodAddPlayNum({
			dataDic,
			success: (res) => {
				console.log(res);
				//更新排行榜数据
				_self.rankListInfo();
			},
			fail: (res) => {
				console.log(res);
			},
			complete: (res) => {
				console.log(res.data);
			},
		})
	},
	// 点击口语训练营
	aldSpoken() {
		app.aldstat.sendEvent('排行榜-点击口语训练营');
	},
	// 点击求助外教
	aldTeacher() {
		app.aldstat.sendEvent('排行榜-点击求助外教');
	}

})